package com.neusoft.hifly.push.sms.aliyun.service.impl;

import java.time.LocalDate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.commons.lang.LocalDateUtil;
import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.push.sms.aliyun.config.AliyunConfig;
import com.neusoft.hifly.push.sms.aliyun.pojo.SendDetailVO;
import com.neusoft.hifly.push.sms.aliyun.service.IAliSmsSendService;

/**
 * 阿里大于短信发送
 */
@Service
public class AliSmsSendServiceImpl implements IAliSmsSendService {

	@Autowired(required = false)
	private AliyunConfig aliyunConfig;

	/**
	 * 后备策略
	 * <p>
	 *  需要在@HystrixCommand注解中添加一个名为fallbackMethod的属性
	 * <p>
	 *  后备方法必须跟使用了@HysrixCommand原始方法在同一个类中
	 * <p>
	 *  后备方法必须是public类型
	 * <p>
	 *  后备方法参数必须和原方法一致
	 *
	 * @param vo
	 *            短信实体
	 * @return 错误信息
	 */
	public SendSmsResponse fallBackSendSms(final SendDetailVO vo) {
		Log.error("系统熔断！");
		final SendSmsResponse r = new SendSmsResponse();
		r.setCode("error");
		r.setMessage("当前访问用户过多，请稍后重试！");
		return r;
	}

	/**
	 * 发送短信
	 *
	 * @param vo
	 *            短信实体
	 * @return 返回值
	 * @throws ClientException
	 *             异常
	 */
	@Override
	@HystrixCommand(fallbackMethod = "fallBackSendSms", ignoreExceptions = SystemErrorException.class, commandProperties = {
			// 请求超时时间
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"),
			// 请求最小次数
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "4"),
			// 失败率阈值%
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
			// 熔断断开后,间隔7s,就尝试访问一次服务,查看服务是否已经恢复
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "7000"),
			// 时间窗口,从监听到第一次失败开始计时
			@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "15000"),
			// 在时间窗口中,收集统计信息的次数。在15s的窗口中每隔3s就收集一次,共5次。
			@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "5") })
	public SendSmsResponse sendSms(final SendDetailVO vo) throws ClientException {
		if (!aliyunConfig.isUse()) {
			Log.error("系统禁止发送阿里大于短信！");
			final SendSmsResponse r = new SendSmsResponse();
			r.setCode("error");
			r.setMessage("系统禁止发送阿里大于短信！");
			return r;
		}
		if (StringUtils.isEmpty(vo.getPhoneNumber())) {
			final SendSmsResponse r = new SendSmsResponse();
			r.setCode("error");
			r.setMessage("待发送手机号不能为空！");
			return r;
		}
		if (StringUtils.isEmpty(vo.getSignName())) {
			final SendSmsResponse r = new SendSmsResponse();
			r.setCode("error");
			r.setMessage("短信签名不能为空！");
			return r;
		}
		if (StringUtils.isEmpty(vo.getTemplateCode())) {
			final SendSmsResponse r = new SendSmsResponse();
			r.setCode("error");
			r.setMessage("短信模板不能为空！");
			return r;
		}

		//可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		//初始化acsClient,暂不支持region化
		final IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", vo.getAccessKeyId(),
				vo.getAccessKeySecret());
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunConfig.getProduct(), aliyunConfig.getDomain());
		final IAcsClient acsClient = new DefaultAcsClient(profile);

		//组装请求对象-具体描述见控制台-文档部分内容
		final SendSmsRequest request = new SendSmsRequest();
		//必填:待发送手机号
		request.setPhoneNumbers(vo.getPhoneNumber());
		//必填:短信签名-可在短信控制台中找到
		request.setSignName(vo.getSignName());
		//必填:短信模板-可在短信控制台中找到
		request.setTemplateCode(vo.getTemplateCode()); // 通用验证码
		//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		request.setTemplateParam(JSON.toJSONString(vo.getTemplateParam()));

		//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
		//request.setSmsUpExtendCode("90997");

		//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		//		request.setOutId("yourOutId");

		//hint 此处可能会抛出异常，注意catch
		final SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

		return sendSmsResponse;
	}

	/**
	 * 查询明细
	 *
	 * @param vo
	 *            短信实体
	 * @param bizId
	 *            发送流水号,从调用发送接口返回值中获取
	 * @return 明细
	 * @throws ClientException
	 *             异常
	 */
	@Override
	public QuerySendDetailsResponse querySendDetails(final SendDetailVO vo, final String bizId) throws ClientException {

		if (!aliyunConfig.isUse()) {
			Log.error("系统禁止发送阿里大于短信！");
			final QuerySendDetailsResponse r = new QuerySendDetailsResponse();
			r.setCode("error");
			r.setMessage("系统禁止发送阿里大于短信！");
			return r;
		}

		//可自助调整超时时间
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		//初始化acsClient,暂不支持region化
		final IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", vo.getAccessKeyId(),
				vo.getAccessKeySecret());
		DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunConfig.getProduct(), aliyunConfig.getDomain());
		final IAcsClient acsClient = new DefaultAcsClient(profile);

		//组装请求对象
		final QuerySendDetailsRequest request = new QuerySendDetailsRequest();
		//必填-号码
		request.setPhoneNumber(vo.getPhoneNumber());
		//可选-流水号
		request.setBizId(bizId);
		//必填-发送日期 支持30天内记录查询，格式yyyyMMdd
		request.setSendDate(LocalDateUtil.dateToStr(LocalDate.now(), LocalDateUtil.DEFAULT_PATTERN_DATETIME_DATE));
		//必填-页大小
		request.setPageSize(10L);
		//必填-当前页码从1开始计数
		request.setCurrentPage(1L);

		//hint 此处可能会抛出异常，注意catch
		final QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

		return querySendDetailsResponse;
	}

}
